/**
 * 同步功能的组合式函数
 * 处理离线数据同步和自动重试逻辑
 */

import { reactive } from 'vue'
import { authState } from '../services/auth'
import { FolderAPI, NoteAPI } from '../services/crudApi'
import { showError, showSuccess, showInfo } from '../services/notification'
import { formatDateTime } from '../utils/dateUtils'
import type { Folder, Note, SyncResult } from '../types'

/**
 * 同步状态接口
 */
interface SyncState {
  isOnlineDataSyncing: boolean
  syncProgress: number
  syncMessage: string
  autoRetryTimer: NodeJS.Timeout | null
  retryCount: number
  maxRetries: number
}

/**
 * 同步功能组合式函数
 */
export function useSync() {
  // 同步状态管理
  const syncState = reactive<SyncState>({
    isOnlineDataSyncing: false,
    syncProgress: 0,
    syncMessage: '',
    autoRetryTimer: null,
    retryCount: 0,
    maxRetries: 3
  })

  /**
   * 停止自动重试同步
   */
  const stopAutoRetrySync = (): void => {
    if (syncState.autoRetryTimer) {
      clearTimeout(syncState.autoRetryTimer)
      syncState.autoRetryTimer = null
    }
    syncState.retryCount = 0
  }

  /**
   * 启动自动重试同步
   */
  const startAutoRetrySync = (handleOfflineDataSync: () => Promise<SyncResult | null>): void => {
    // 清除之前的定时器
    if (syncState.autoRetryTimer) {
      clearTimeout(syncState.autoRetryTimer)
    }
    
    // 检查是否超过最大重试次数
    if (syncState.retryCount >= syncState.maxRetries) {
      console.log('已达到最大重试次数，停止自动重试')
      showError('数据同步多次失败，请检查网络连接或稍后手动重试', '同步失败')
      return
    }
    
    // 计算重试延迟时间（递增延迟：30秒、60秒、120秒）
    const retryDelay = Math.min(30000 * Math.pow(2, syncState.retryCount), 120000)
    
    console.log(`将在 ${retryDelay / 1000} 秒后进行第 ${syncState.retryCount + 1} 次重试`)
    
    syncState.autoRetryTimer = setTimeout(async () => {
      syncState.retryCount++
      console.log(`开始第 ${syncState.retryCount} 次自动重试同步`)
      
      try {
        const syncResult = await handleOfflineDataSync()
        
        if (syncResult && syncResult.totalCount > 0) {
          if (syncResult.success) {
            showSuccess(`重试成功！已同步 ${syncResult.totalCount} 项数据到云端`, '同步完成')
            // 重置重试计数
            syncState.retryCount = 0
          } else {
            showInfo(`第 ${syncState.retryCount} 次重试：${syncResult.failedCount}/${syncResult.totalCount} 项数据仍然失败`, '重试中')
            // 继续重试
            startAutoRetrySync(handleOfflineDataSync)
          }
        } else {
          // 没有待同步数据，重置重试计数
          syncState.retryCount = 0
        }
      } catch (error) {
        console.error(`第 ${syncState.retryCount} 次重试失败:`, error)
        // 继续重试
        startAutoRetrySync(handleOfflineDataSync)
      }
    }, retryDelay)
  }

  /**
   * 处理离线数据同步
   */
  const handleOfflineDataSync = async (
    folders: Folder[],
    notes: Note[],
    updateFolders: (folders: Folder[]) => void,
    updateNotes: (notes: Note[]) => void,
    saveAppData: () => Promise<void>
  ): Promise<SyncResult | null> => {
    if (!authState.isLoggedIn) {
      console.log('用户未登录，跳过离线数据同步')
      return null
    }

    try {
      syncState.isOnlineDataSyncing = true
      syncState.syncProgress = 0
      syncState.syncMessage = '正在检查待同步数据...'

      // 获取待同步的数据
      const pendingFolders = folders.filter(f => f.syncStatus === 'pending' || f.syncStatus === 'modified')
      const pendingNotes = notes.filter(n => n.syncStatus === 'pending' || n.syncStatus === 'modified')

      const totalItems = pendingFolders.length + pendingNotes.length

      if (totalItems === 0) {
        console.log('没有待同步的数据')
        syncState.isOnlineDataSyncing = false
        return { success: true, failedCount: 0, totalCount: 0 }
      }

      console.log(`发现 ${totalItems} 项待同步数据：${pendingFolders.length} 个文件夹，${pendingNotes.length} 个笔记`)
      showInfo(`发现 ${totalItems} 项待同步数据，开始同步...`, '数据同步')

      let syncedItems = 0

      // 同步文件夹
      for (const folder of pendingFolders) {
        try {
          syncState.syncMessage = `正在同步文件夹: ${folder.name}`
          
          if (folder.syncStatus === 'pending') {
            // 创建新文件夹
            const createdFolder = await FolderAPI.create({
              name: folder.name,
              count: folder.count,
              isDefault: folder.isDefault || false,
              isShared: folder.isShared || false,
              parentId: folder.parentId,
              createdAt: folder.createdAt,
              updatedAt: folder.updatedAt
            })
            
            if (createdFolder) {
              // 更新本地文件夹ID和状态
              const oldId = folder.id
              Object.assign(folder, createdFolder, { syncStatus: 'synced' })
              
              // 更新引用该文件夹的笔记
              notes.forEach(note => {
                if (note.folderId === oldId) {
                  note.folderId = createdFolder.id
                }
              })
              
              console.log(`文件夹同步成功: ${folder.name}`)
            }
          } else if (folder.syncStatus === 'modified') {
            // 更新现有文件夹
            const updatedFolder = await FolderAPI.update(folder.id, {
              name: folder.name,
              isShared: folder.isShared,
              parentId: folder.parentId,
              updatedAt: folder.updatedAt
            })
            
            if (updatedFolder) {
              Object.assign(folder, updatedFolder, { syncStatus: 'synced' })
              console.log(`文件夹更新成功: ${folder.name}`)
            }
          }
          
          syncedItems++
          syncState.syncProgress = Math.round((syncedItems / totalItems) * 100)
        } catch (error) {
          console.error(`同步文件夹失败: ${folder.name}`, error)
          // 继续同步其他项目
        }
      }

      // 同步笔记
      for (const note of pendingNotes) {
        try {
          syncState.syncMessage = `正在同步笔记: ${note.title}`
          
          if (note.syncStatus === 'pending') {
            // 创建新笔记
            const createdNote = await NoteAPI.create({
              title: note.title,
              content: note.content,
              folderId: note.folderId,
              createdAt: note.createdAt,
              updatedAt: note.updatedAt,
              tags: note.tags || []
            })
            
            if (createdNote) {
              Object.assign(note, createdNote, { syncStatus: 'synced' })
              console.log(`笔记同步成功: ${note.title}`)
            }
          } else if (note.syncStatus === 'modified') {
            // 更新现有笔记
            const updatedNote = await NoteAPI.update(note.id, {
              title: note.title,
              content: note.content,
              folderId: note.folderId,
              updatedAt: note.updatedAt,
              tags: note.tags
            })
            
            if (updatedNote) {
              Object.assign(note, updatedNote, { syncStatus: 'synced' })
              console.log(`笔记更新成功: ${note.title}`)
            }
          }
          
          syncedItems++
          syncState.syncProgress = Math.round((syncedItems / totalItems) * 100)
        } catch (error) {
          console.error(`同步笔记失败: ${note.title}`, error)
          // 继续同步其他项目
        }
      }

      // 保存同步后的数据
      await saveAppData()
      
      syncState.syncMessage = '同步完成'
      syncState.syncProgress = 100
      
      showSuccess(`成功同步 ${syncedItems} 项数据`, '同步完成')
      console.log(`离线数据同步完成，共同步 ${syncedItems}/${totalItems} 项`)
      
      const failedCount = totalItems - syncedItems
      const result: SyncResult = {
        success: failedCount === 0,
        failedCount,
        totalCount: totalItems
      }
      
      // 如果完全同步成功，停止自动重试
      if (result.success) {
        stopAutoRetrySync()
      }
      
      return result
      
    } catch (error) {
      console.error('离线数据同步失败:', error)
      showError('离线数据同步失败，请稍后重试', '同步错误')
      return null
    } finally {
      syncState.isOnlineDataSyncing = false
      syncState.syncProgress = 0
      syncState.syncMessage = ''
    }
  }

  return {
    syncState,
    startAutoRetrySync,
    stopAutoRetrySync,
    handleOfflineDataSync
  }
}